<script setup>
import { ref, defineProps } from 'vue'
const props = defineProps({
  modelValue: {
    type: Number,
    default: 1
  }
})
const emit = defineEmits(['update:modelValue']);
const handleSub = () => {
      if (props.modelValue <= 1) {
        return
      }
      emit('update:modelValue', props.modelValue - 1);
    }
const handleAdd = () => {
  emit('update:modelValue', props.modelValue + 1);
    }
const handleChange = (e) => {
      // console.log(e.target.value)
      const num = +e.target.value // 转数字处理 (1) 数字 (2) NaN

      // 输入了不合法的文本 或 输入了负值，回退成原来的 value 值
      if (isNaN(num) || num < 1) {

        // console.log("数值是" + value)
        
        e.target.value = props.modelValue
        return
      }
      emit('update:modelValue', num);

    }

</script>
<template>
  <div class="count-box">
    <button @click="handleSub" class="minus">-</button>
    <input :value="modelValue" @change="handleChange" class="inp" type="text">
    <button @click="handleAdd" class="add">+</button>
  </div>
</template>
    

<style lang="less" scoped>
.count-box {
  width: 110px;
  display: flex;
  .add, .minus {
    width: 30px;
    height: 30px;
    outline: none;
    border: none;
    background-color: #efefef;
  }
  .inp {
    width: 40px;
    height: 30px;
    outline: none;
    border: none;
    margin: 0 5px;
    background-color: #efefef;
    text-align: center;
  }
}
</style>
